package hku.cs.lunuo.rank;

import hku.cs.lunuo.rank.model.Label;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;



public class StmtResult {
	public List<StmtResultUnit> data = new LinkedList<StmtResultUnit>();

	public void rank() {
		Collections.sort(data);
		Collections.reverse(data);
		int size = data.size();
		if (size > 0)
			data.get(size - 1).rank = size;

		for (int i = size - 2; i >= 0; i--) {
			StmtResultUnit r = data.get(i);
			if (r.compareTo(data.get(i + 1)) == 0)
				r.rank = data.get(i + 1).rank;
			else
				r.rank = i + 1;
		}
		
	}

	public void add(String klassName, Integer ln, Label label) {
		data.add(new StmtResultUnit(klassName, ln, label));
	}

	public void toXML(File f) {
		Element xmlRoot = new Element("ranklist");
		Document xmlDoc = new Document(xmlRoot);
		xmlRoot.setAttribute("totalExecute", String.valueOf(data.size()));
		int i = 0;
		for(StmtResultUnit sru : data) {
			Element xmlStmt = new Element("statement");
			xmlStmt.setAttribute("index", Integer.toString(++i));
			sru.toXML(xmlStmt);
			xmlRoot.addContent(xmlStmt);
		}
		
		try {
			new XMLOutputter().output(xmlDoc, new FileOutputStream(f));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Iterator iterator(){
		return data.iterator();
	}
	
	public int getSize() {
		return data.size();
	}
}